package com.sghd.candy.module.charge.manager;

import com.sghd.candy.module.player.manager.Player;
import com.sghd.common.ramcache.orm.Accessor;
import com.sghd.common.ramcache.orm.Querier;
import com.sghd.common.utils.id.other.NormalIdGenerator;
import com.sghd.common.utils.json.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author frank
 */
@Component
public class ChargeLogManager {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private Accessor accessor;
    @Autowired
    private Querier querier;
    @Value("${platformId}")
    private short operator;
    @Value("${area}")
    private short area;

    private BlockingQueue<ChargeLog> queues = new LinkedBlockingQueue<>();

    private NormalIdGenerator generator;

    @PostConstruct
    void initialize() {
        long[] limits = NormalIdGenerator.getLimits(operator, area);
        Long max = querier.unique(ChargeLog.class, Long.class, ChargeLog.MAX_ID, limits[0], limits[1]);
        generator = new NormalIdGenerator(operator, area, max);
        init();
    }

    protected void init() {
        Thread thread = new Thread("充值日志记录线程") {
            @Override
            public void run() {
                while (!Thread.interrupted()) {
                    try {
                        ChargeLog log = queues.take();
                        logger.debug("充值日志订单[{}]写入数据库！", log.getId());
                        accessor.save(ChargeLog.class, log);
                    } catch (InterruptedException e) {
                        logger.error("", e);
                    }
                }
            }
        };
        thread.setDaemon(true);
        thread.start();
    }

    @PreDestroy
    void shutdown() {
        int i = 0;
        while (!queues.isEmpty()) {
            if (i > 30) {
                logger.error("超时充值日志队列停服回写:", JsonUtils.object2String(queues));
                break;
            }
            try {
                Thread.sleep(1000);
                i++;
            } catch (InterruptedException e) {
            }
        }
    }

    /**
     * 获取订单信息
     * @param orderId
     * @return
     */
    public ChargeLog getChargeLog(long orderId) {
        return querier.unique(ChargeLog.class, ChargeLog.ORDER_ID, orderId);
    }


    public void addLog(Player player, long orderId, String reward, int money, String ip) {
        boolean first = false;
        addLog(player, orderId, reward, money, ip, first);
    }

    public void addLog(Player player, long orderId, String reward, int money, String ip, boolean isFirst) {
        long playerId = player.getId();
        long id = generator.getNext();
        ChargeLog log = ChargeLog.valueOf(id, playerId, orderId, reward, money, ip, isFirst);
        //保存充值日志
        queues.add(log);

    }
}
